'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Calendar } from '@/components/ui/calendar'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { CalendarIcon, MapPinIcon, PhoneIcon, ClockIcon, UserIcon, CreditCardIcon, CheckCircleIcon } from 'lucide-react'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import { api, type Hospital, type Department, type Doctor, type TimeSlot, type CreateAppointmentRequest, type PatientInfo } from '@/lib/api'
import { toast } from 'sonner'

interface AppointmentBookingFormProps {
  open: boolean
  onClose: () => void
  onSuccess?: (appointment: any) => void
}

interface AppointmentState {
  step: 'hospital' | 'department' | 'doctor' | 'time' | 'patient' | 'confirm'
  selectedHospital: Hospital | null
  selectedDepartment: Department | null
  selectedDoctor: Doctor | null
  selectedDate: Date | null
  selectedTimeSlot: TimeSlot | null
  patientInfo: PatientInfo
}

const initialState: AppointmentState = {
  step: 'hospital',
  selectedHospital: null,
  selectedDepartment: null,
  selectedDoctor: null,
  selectedDate: null,
  selectedTimeSlot: null,
  patientInfo: {
    name: '',
    phone: '',
    idCard: ''
  }
}

export default function AppointmentBookingForm({ open, onClose, onSuccess }: AppointmentBookingFormProps) {
  const [state, setState] = useState<AppointmentState>(initialState)
  const [loading, setLoading] = useState(false)
  const [hospitals, setHospitals] = useState<Hospital[]>([])
  const [departments, setDepartments] = useState<Department[]>([])
  const [doctors, setDoctors] = useState<Doctor[]>([])
  const [timeSlots, setTimeSlots] = useState<TimeSlot[]>([])

  // 重置状态
  useEffect(() => {
    if (open) {
      setState(initialState)
      loadHospitals()
    }
  }, [open])

  const loadHospitals = async () => {
    try {
      setLoading(true)
      const response = await api.appointment.getHospitals({ page: 1, limit: 50 })
      if (response.success) {
        setHospitals(response.data.hospitals)
      }
    } catch (error) {
      console.error('加载医院列表失败:', error)
      toast.error('加载医院列表失败')
    } finally {
      setLoading(false)
    }
  }

  // 选择医院
  const selectHospital = async (hospital: Hospital) => {
    setState(prev => ({ ...prev, selectedHospital: hospital, step: 'department' }))
    try {
      setLoading(true)
      const response = await api.appointment.getDepartments({ hospitalId: hospital.id })
      if (response.success) {
        // 兼容新的数据结构
        const departmentList = response.data.departments || response.data || []
        setDepartments(departmentList)
        console.log('加载科室数据成功:', {
          hospitalId: hospital.id,
          compatibleHospitalId: response.data.compatibleHospitalId,
          departments: departmentList.length
        })
      }
    } catch (error) {
      console.error('加载科室列表失败:', error)
      toast.error('加载科室列表失败')
    } finally {
      setLoading(false)
    }
  }

  // 选择科室
  const selectDepartment = async (department: Department) => {
    setState(prev => ({ ...prev, selectedDepartment: department, step: 'doctor' }))
    try {
      setLoading(true)
      const response = await api.appointment.getDoctors({ 
        hospitalId: state.selectedHospital?.id, 
        departmentId: department.id 
      })
      if (response.success) {
        setDoctors(response.data.doctors || [])
      }
    } catch (error) {
      console.error('加载医生列表失败:', error)
      toast.error('加载医生列表失败')
    } finally {
      setLoading(false)
    }
  }

  // 选择医生
  const selectDoctor = (doctor: Doctor) => {
    setState(prev => ({ ...prev, selectedDoctor: doctor, step: 'time' }))
  }

  // 选择日期
  const selectDate = async (date: Date) => {
    setState(prev => ({ ...prev, selectedDate: date }))
    if (state.selectedDoctor) {
      try {
        setLoading(true)
        const response = await api.appointment.getTimeSlots({
          doctorId: state.selectedDoctor.id,
          date: format(date, 'yyyy-MM-dd')
        })
        if (response.success) {
          setTimeSlots(response.data)
        }
      } catch (error) {
        console.error('加载时间段失败:', error)
        toast.error('加载时间段失败')
      } finally {
        setLoading(false)
      }
    }
  }

  // 选择时间段
  const selectTimeSlot = (timeSlot: TimeSlot) => {
    setState(prev => ({ ...prev, selectedTimeSlot: timeSlot, step: 'patient' }))
  }

  // 提交预约
  const submitAppointment = async () => {
    if (!state.selectedHospital || !state.selectedDepartment || !state.selectedDoctor || 
        !state.selectedDate || !state.selectedTimeSlot || !state.patientInfo.name || !state.patientInfo.phone) {
      toast.error('请填写完整的预约信息')
      return
    }

    try {
      setLoading(true)
      const appointmentData: CreateAppointmentRequest = {
        hospitalId: state.selectedHospital.id,
        hospitalName: state.selectedHospital.name,
        departmentId: state.selectedDepartment.id,
        departmentName: state.selectedDepartment.name,
        doctorId: state.selectedDoctor.id,
        doctorName: state.selectedDoctor.name,
        appointmentDate: format(state.selectedDate, 'yyyy-MM-dd'),
        timeSlot: state.selectedTimeSlot.time,
        price: state.selectedTimeSlot.price,
        patientInfo: state.patientInfo
      }

      const response = await api.appointment.createAppointment(appointmentData)
      if (response.success) {
        toast.success('预约成功！')
        onSuccess?.(response.data.appointment)
        onClose()
      } else {
        toast.error(response.message || '预约失败')
      }
    } catch (error) {
      console.error('提交预约失败:', error)
      toast.error('网络错误，请稍后重试')
    } finally {
      setLoading(false)
    }
  }

  // 返回上一步
  const goBack = () => {
    const stepOrder = ['hospital', 'department', 'doctor', 'time', 'patient', 'confirm']
    const currentIndex = stepOrder.indexOf(state.step)
    if (currentIndex > 0) {
      setState(prev => ({ ...prev, step: stepOrder[currentIndex - 1] as any }))
    }
  }

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>在线预约挂号</DialogTitle>
          <DialogDescription>
            {state.step === 'hospital' && '请选择医院'}
            {state.step === 'department' && '请选择科室'}
            {state.step === 'doctor' && '请选择医生'}
            {state.step === 'time' && '请选择时间'}
            {state.step === 'patient' && '请填写患者信息'}
            {state.step === 'confirm' && '请确认预约信息'}
          </DialogDescription>
        </DialogHeader>

        <div className="py-4">
          {/* 步骤指示器 */}
          <div className="flex items-center justify-center mb-6">
            <div className="flex items-center space-x-2">
              {[
                { key: 'hospital', label: '医院' },
                { key: 'department', label: '科室' },
                { key: 'doctor', label: '医生' },
                { key: 'time', label: '时间' },
                { key: 'patient', label: '信息' },
                { key: 'confirm', label: '确认' },
              ].map((item, index) => {
                const isActive = state.step === item.key
                const isCompleted = ['hospital', 'department', 'doctor', 'time', 'patient'].indexOf(state.step) > 
                                 ['hospital', 'department', 'doctor', 'time', 'patient'].indexOf(item.key)
                
                return (
                  <div key={item.key} className="flex items-center">
                    <div className={`
                      flex items-center justify-center w-8 h-8 rounded-full text-sm font-medium
                      ${isActive ? 'bg-blue-500 text-white' : 
                        isCompleted ? 'bg-green-500 text-white' : 
                        'bg-gray-200 text-gray-500'}
                    `}>
                      {index + 1}
                    </div>
                    <span className={`ml-1 text-sm ${isActive ? 'text-blue-600 font-medium' : 'text-gray-500'}`}>
                      {item.label}
                    </span>
                    {index < 5 && <div className="w-6 h-0.5 bg-gray-300 ml-2" />}
                  </div>
                )
              })}
            </div>
          </div>

          {/* 选择医院 */}
          {state.step === 'hospital' && (
            <div className="grid gap-4 md:grid-cols-2">
              {hospitals.map((hospital) => (
                <Card key={hospital.id} className="cursor-pointer hover:bg-gray-50 transition-colors"
                      onClick={() => selectHospital(hospital)}>
                  <CardContent className="p-4">
                    <div className="flex justify-between items-start mb-2">
                      <h3 className="font-semibold text-lg">{hospital.name}</h3>
                      <Badge variant="outline">{hospital.level}</Badge>
                    </div>
                    <div className="flex items-center text-gray-600 text-sm mb-1">
                      <MapPinIcon className="w-4 h-4 mr-1" />
                      {hospital.address}
                    </div>
                    <div className="flex items-center text-gray-600 text-sm">
                      <PhoneIcon className="w-4 h-4 mr-1" />
                      {hospital.phone}
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}

          {/* 选择科室 */}
          {state.step === 'department' && (
            <div className="space-y-4">
              <div className="text-sm text-gray-600">
                已选择：{state.selectedHospital?.name}
              </div>
              <div className="grid gap-4 md:grid-cols-3">
                {departments.map((department) => (
                  <Card key={department.id} className="cursor-pointer hover:bg-gray-50 transition-colors"
                        onClick={() => selectDepartment(department)}>
                    <CardContent className="p-4">
                      <h3 className="font-semibold text-lg mb-2">{department.name}</h3>
                      <p className="text-gray-600 text-sm mb-3">{department.description}</p>
                      <div className="flex justify-between text-sm text-gray-500">
                        <span>{department.doctorCount} 位医生</span>
                        <span>{department.availableSlots} 个可用时段</span>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </div>
          )}

          {/* 选择医生 */}
          {state.step === 'doctor' && (
            <div className="space-y-4">
              <div className="text-sm text-gray-600">
                已选择：{state.selectedHospital?.name} - {state.selectedDepartment?.name}
              </div>
              <div className="grid gap-4 md:grid-cols-2">
                {doctors.map((doctor) => (
                  <Card key={doctor.id} className="cursor-pointer hover:bg-gray-50 transition-colors"
                        onClick={() => selectDoctor(doctor)}>
                    <CardContent className="p-4">
                      <div className="flex items-start space-x-4">
                        <div className="w-12 h-12 bg-gray-200 rounded-full flex items-center justify-center">
                          <UserIcon className="w-6 h-6 text-gray-400" />
                        </div>
                        <div className="flex-1">
                          <div className="flex justify-between items-start mb-2">
                            <h3 className="font-semibold text-lg">{doctor.name}</h3>
                            <Badge variant="outline">{doctor.title}</Badge>
                          </div>
                          <p className="text-gray-600 text-sm mb-2">{doctor.specialty}</p>
                          <p className="text-gray-500 text-sm mb-2">{doctor.experience}</p>
                          <div className="flex justify-between items-center">
                            <div className="flex items-center">
                              <span className="text-yellow-400">★★★★★</span>
                              <span className="ml-1 text-sm text-gray-600">{doctor.rating}</span>
                            </div>
                            <div className="flex items-center">
                              <CreditCardIcon className="w-4 h-4 mr-1 text-gray-400" />
                              <span className="text-lg font-semibold text-red-600">¥{doctor.price}</span>
                            </div>
                          </div>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </div>
          )}

          {/* 选择时间 */}
          {state.step === 'time' && (
            <div className="space-y-4">
              <div className="text-sm text-gray-600">
                已选择：Dr. {state.selectedDoctor?.name}
              </div>
              <div className="grid gap-6 md:grid-cols-2">
                <div>
                  <Label className="text-base font-medium mb-4 block">选择日期</Label>
                  <Calendar
                    mode="single"
                    selected={state.selectedDate || undefined}
                    onSelect={(date) => date && selectDate(date)}
                    disabled={(date) => date < new Date() || date > new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)}
                    locale={zhCN}
                    className="rounded-md border"
                  />
                </div>
                <div>
                  <Label className="text-base font-medium mb-4 block">选择时间段</Label>
                  {state.selectedDate && (
                    <div className="grid gap-2">
                      {timeSlots.map((slot) => (
                        <Button
                          key={slot.time}
                          variant={slot.available ? "outline" : "secondary"}
                          disabled={!slot.available}
                          className="justify-between"
                          onClick={() => selectTimeSlot(slot)}
                        >
                          <span>{slot.time}</span>
                          <span className="text-red-600">¥{slot.price}</span>
                          {!slot.available && (
                            <span className="text-xs text-gray-500 ml-2">
                              {slot.reason || '已满'}
                            </span>
                          )}
                        </Button>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}

          {/* 患者信息 */}
          {state.step === 'patient' && (
            <div className="space-y-4">
              <div className="text-sm text-gray-600">
                预约时间：{state.selectedDate && format(state.selectedDate, 'yyyy年MM月dd日', { locale: zhCN })} {state.selectedTimeSlot?.time}
              </div>
              <div className="grid gap-4 md:grid-cols-2">
                <div>
                  <Label htmlFor="name">患者姓名 *</Label>
                  <Input
                    id="name"
                    value={state.patientInfo.name}
                    onChange={(e) => setState(prev => ({
                      ...prev,
                      patientInfo: { ...prev.patientInfo, name: e.target.value }
                    }))}
                    placeholder="请输入患者姓名"
                  />
                </div>
                <div>
                  <Label htmlFor="phone">联系电话 *</Label>
                  <Input
                    id="phone"
                    value={state.patientInfo.phone}
                    onChange={(e) => setState(prev => ({
                      ...prev,
                      patientInfo: { ...prev.patientInfo, phone: e.target.value }
                    }))}
                    placeholder="请输入联系电话"
                  />
                </div>
                <div className="md:col-span-2">
                  <Label htmlFor="idCard">身份证号</Label>
                  <Input
                    id="idCard"
                    value={state.patientInfo.idCard}
                    onChange={(e) => setState(prev => ({
                      ...prev,
                      patientInfo: { ...prev.patientInfo, idCard: e.target.value }
                    }))}
                    placeholder="请输入身份证号（可选）"
                  />
                </div>
              </div>
            </div>
          )}

          {/* 确认预约 */}
          {state.step === 'confirm' && (
            <div className="space-y-6">
              <div className="grid gap-4 md:grid-cols-2">
                <div>
                  <Label className="text-sm font-medium text-gray-500">医院</Label>
                  <p className="font-medium">{state.selectedHospital?.name}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium text-gray-500">科室</Label>
                  <p className="font-medium">{state.selectedDepartment?.name}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium text-gray-500">医生</Label>
                  <p className="font-medium">{state.selectedDoctor?.name} {state.selectedDoctor?.title}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium text-gray-500">就诊时间</Label>
                  <p className="font-medium">
                    {state.selectedDate && format(state.selectedDate, 'yyyy年MM月dd日', { locale: zhCN })} {state.selectedTimeSlot?.time}
                  </p>
                </div>
                <div>
                  <Label className="text-sm font-medium text-gray-500">患者姓名</Label>
                  <p className="font-medium">{state.patientInfo.name}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium text-gray-500">联系电话</Label>
                  <p className="font-medium">{state.patientInfo.phone}</p>
                </div>
              </div>
              
              <div className="border-t pt-4">
                <div className="flex justify-between items-center">
                  <span className="text-lg font-medium">挂号费用</span>
                  <span className="text-2xl font-bold text-red-600">¥{state.selectedTimeSlot?.price}</span>
                </div>
              </div>
            </div>
          )}
        </div>

        <DialogFooter className="flex justify-between">
          <div className="flex space-x-2">
            {state.step !== 'hospital' && (
              <Button variant="outline" onClick={goBack}>
                上一步
              </Button>
            )}
            <Button variant="outline" onClick={onClose}>
              取消
            </Button>
          </div>
          <div>
            {state.step === 'patient' && (
              <Button 
                onClick={() => setState(prev => ({ ...prev, step: 'confirm' }))}
                disabled={!state.patientInfo.name || !state.patientInfo.phone}
              >
                下一步：确认预约
              </Button>
            )}
            {state.step === 'confirm' && (
              <Button onClick={submitAppointment} disabled={loading}>
                {loading ? '正在提交...' : '确认预约'}
              </Button>
            )}
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}